<template>
  <div class="chat-left">
    <div class="search">
      <el-input placeholder="请输入关键字" v-model="searchKeyword" clearable class="custom-input">
        <el-button slot="append" icon="el-icon-search"></el-button>
      </el-input>
    </div>
    <!-- 列表 -->
    <div class="list">
      <div v-for="user in filteredList" :key="user.id" class="user-item" @click="select(user)">
        <img src="../assets/touxiang.jpg" class="touxiang">
        <div class="user-info">
          <div class="user-name">{{ user.name }}</div>
          <div class="text">暂无消息....</div>
          <div class="user-content">2025-02-13 13:14:52</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex';

export default {
  name: 'ChatZuo',
  data() {
    return {
      searchKeyword: '',
    };
  },
  // 移除多余的 watch 部分
  computed: {
    ...mapState({
      userList: state => state.chat.userList,
      selectedUserId: state => state.chat.selectedUserId
    }),
    // 搜索过滤（使用计算属性自动响应依赖变化）
    searchUsers() {
      const kw = this.searchKeyword.trim().toLowerCase();
      return this.userList.filter(user =>
        (user.name || '').toLowerCase().includes(kw)
      );
    },
    filteredList() {
      if (!this.searchKeyword) {
        return this.userList;
      }
      return this.searchUsers;
    }
  },
  mounted() {
    this.getUserList();
  },
  methods: {
    ...mapActions(['getUserList']),
    // 选择用户
    select(user) {
      this.$store.commit('setSelectedUserId', user.id);
      this.$bus.$emit('appear', user.name); // 触发事件
    },
    // 过滤用户列表（此方法不再需要，因为计算属性已经实现了过滤功能）
    // filterList(keyword) {
    //   if (!keyword) {
    //     // 如果关键字为空，显示全部用户
    //     this.filteredList = [...this.userList];
    //   } else {
    //     // 否则过滤出包含关键字的用户
    //     this.filteredList = this.userList.filter(user => {
    //       return user.name.includes(keyword);
    //     });
    //   }
    // },
    // 返回首页
    // esc() {
    //   this.$router.push('/');  // 使用路由跳转方法
    // }
  }
};
</script>

<style lang="sass" scoped>
.chat-left {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.search {
  height: 65px;
}

.list {
  width: 100%;
  flex: 1;
  height: calc(100vh - 65px);
  overflow-y: auto;
  overflow-x: hidden;
}

.text {
  font-size: 14px;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 2px solid #eee;
  max-width: 100%;
}

.touxiang {
  width: 50px;
  height: 50px;
  margin-right: 10px;
  border-radius: 50%;
}

.user-info {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: bold;
}

.user-content {
  font-size: 13px;
  padding-left: 100px;
  margin-top: -40px;
  color: #666;
}

.custom-input {
  width: 270px;
  margin-left: 20px;
  margin-top: 10px;
}
</style>